<?php

namespace app\common\helper;
use app\common\logic\common\CommonLogic;
use app\common\model\Authorization;
use app\common\model\Goods;
use app\common\model\Log;
use app\common\model\MoneyLog;
use app\common\model\User;
use think\Exception;
use think\exception\HttpResponseException;

if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
require_once root_path()  . 'extend' . DS . 'sdk-php' . DS . 'src'. DS . 'autoload.php';

class SelfDouHelper
{
    protected $appKey;
    protected $appSecret;
    protected $api_base;
    protected $daren_id;
    protected $accessToken;
    public function __construct() {
        $config = cache('config');
        $this->appKey = "7300864516865132059";
        $this->appSecret = "f4700dbc-1ac0-45eb-9b6d-8dbcda59c40b";
        $this->daren_id = "dy_107262659644153708852_40521_2375443458";
        $this->api_base = "https://openapi-fxg.jinritemai.com";
        
        \GlobalConfig::getGlobalConfig()->appKey = $this->appKey;
        \GlobalConfig::getGlobalConfig()->appSecret = $this->appSecret;
    }
    
    public function getAccessToken($code)
    {
        $this->accessToken = \AccessTokenBuilder::build($code,ACCESS_TOKEN_CODE);
        $auth = Authorization::where('id',1)->find();
        $auth->save([
            "code" => $code,
            "access_token" => $this->accessToken->getAccessToken(),
            "refresh_token" => $this->accessToken->getRefreshToken(),
            "expire_in" => $this->accessToken->getExpireIn(),
            "create_time" => time(),
            "expire_time" => time() + $this->accessToken->getExpireIn(),
        ]);
        return $this;
    }
    
    // 使用定时任务刷新token 每20分钟检测一次
    public function refreshToken()
    {
        $auth = Authorization::where('id',1)->find();
        if (($auth->getData('expire_time') - 60 * 60) < time()) {
            $this->accessToken = \AccessTokenBuilder::refresh($auth['refresh_token']);
            $auth->save([
                "access_token" => $this->accessToken->getAccessToken(),
                "refresh_token" => $this->accessToken->getRefreshToken(),
                "expire_in" => $this->accessToken->getExpireIn(),
                "create_time" => time(),
                "expire_time" => time() + $this->accessToken->getExpireIn(),
            ]);
        }
        $this->accessToken = \AccessTokenBuilder::parse($auth->access_token);
        return $this;
    }
    
    public function getToken()
    {
        return $this->accessToken;
    }
    public function getRefreshToken()
    {
        if ($this->accessToken) {
            return $this->accessToken->getRefreshToken();
        }
        return  "";
    }
    public function translateUrl($url,$external_info)
    {
        $request = new \BuyinKolProductShareRequest();
        $param = new \BuyinKolProductShareParam();
        $request->setParam($param);
        $param->pid = $this->daren_id;
        $param->product_url = $url;
        $param->external_info = $external_info;
        $param->need_qr_code = false;
        $param->platform = 0;
        $param->use_coupon = false;
        $param->need_share_link = false;
        $param->need_zlink = false;
        $token = $this->refreshToken()->getToken();
        $response = $request->execute($token);
        return (array) $response;
    }
    
    public function msgNotify()
    {
        $body = file_get_contents("php://input");
        $post_sign = request()->header("event-sign");
        $post_appid = request()->header("app-id");
        if ($post_appid !== $this->appKey) {
            file_put_contents("msg.txt","appKey error", FILE_APPEND);
            return false;
        }
        $sign = md5($this->appKey . $body . $this->appSecret);
        if ($sign !== $post_sign) {
            file_put_contents("msg.txt","sign error", FILE_APPEND);
            return false;
        }
        $data = json_decode($body);
        queue("app\common\job\DouYin@msgNotify",$data);
        file_put_contents("msg.txt",date("Y-m-d H:i:s")."添加任务队列成功"."\r\n", FILE_APPEND);
        throw new HttpResponseException(json([
            "code" => 0,
            "msg" => "success"
        ]));
    }
    
    // 达人授权
    public function getAuth()
    {
        $state = CommonLogic::makeOrderNo();
        $url = "https://buyin.jinritemai.com/dashboard/institution/through-power?app_id={$this->appKey}&state={$state}";
        return $url;
    }
    
    public function notifyHandle($data)
    {
        echo 'beg-' . count($data) . "\r\n";
        try {
            foreach ($data as $temp) {
                if ($temp['tag'] == 418) {
                    $item = json_decode($temp['data'],true);
                    $exit = Log::where("order_no",$item['pid_info']['external_info'])->find();
                    if ($exit) {
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'PAY_SUCC') {
                            $goods = Goods::where("id",$exit->goods_id)->find();
                            if ($goods) {
                                if ($goods->stock > 0) {
                                    $goods->stock--;
                                    $goods->save();
                                }
                            }
                            $exit->flow_point = 'PAY_SUCC';
                            $exit->status = 1;// 已经支付 待确认收货返佣
                        }
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'CONFIRM') {
                            $exit->flow_point = 'CONFIRM';
                            $exit->status = 2;// 确认收货 已返佣
                            $user = User::where("id", $exit->user_id)->find();
                            if ($user) {
                                $user->money += $exit->next_money;
                                $user->save();
                            }
                            MoneyLog::create([
                                "user_id" => $user->id,
                                "money" => $exit->next_money,
                                "is_add" => 1,
                                "content" => "返佣"
                            ]);
                        }
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'REFUND') {
                            $exit->flow_point = 'REFUND';
                            if ($exit->status == 2) { // 已经返佣的 退还佣金
                                $user = User::where("id",$exit->user_id)->find();
                                if ($user) {
                                    $user->money -= $exit->next_money;
                                    $user->save();
                                }
                                MoneyLog::create([
                                    "user_id" => $user->id,
                                    "money" => $exit->next_money,
                                    "is_add" => 0,
                                    "content" => "退款扣佣"
                                ]);
                            }
                            $exit->status = -2; //码失效
                        }
                        $exit->order_id = $item['order_id'];
                        $exit->pay_time = strtotime($item['pay_success_time']);
                        $exit->total_pay_amount = round($item['total_pay_amount'] / 100,2);
                        $exit->save();
                    }
                }
            }
            echo '$exception->getMessage()'  . "\r\n";;
        } catch (Exception $exception) {
            echo $exception->getMessage()  . "\r\n";
        }
    }
    
    // 授权回调 队列执行
    public function authNotify($data)
    {
        queue("app\common\job\DouYin@authNotify",$data);
    }
    
    // 解析回调
    public function decrypt($sSrc) {
        if (!$sSrc) return false;
        try {
            $msg = $sSrc;
            $key = $this->appSecret;
            $key2 = str_replace('-','',$key);
            $encryptedData =$msg;
            $key = $key2;
            $decryptionMethod = "AES-256-CBC";
            $blockSize = openssl_cipher_iv_length($decryptionMethod);
            $iv = substr($key2, 0, $blockSize);
            $plaintext = openssl_decrypt($encryptedData, $decryptionMethod, $key, 0, $iv);
            if ($plaintext === false) {
                echo openssl_error_string();
                return  false;
            }
            $data = json_decode($plaintext,true);
            if ($data['msg_type'] == 2) {
                $msg = json_decode($data['msg'],true);
                $accessToken = \AccessTokenBuilder::build($msg['code']);
                $exit = Authorization::where("authority_id",$msg['authority_id'])->find();
                if (!$exit) {
                    $exit = Authorization::create([
                        "app_id" => $msg['app_id'],
                        "authority_id" => $msg['authority_id'],
                        "code" => $msg['code'],
                        "access_token" => $accessToken->getAccessToken(),
                        "refresh_token" => $accessToken->getRefreshToken(),
                        "expire_in" => $accessToken->getExpireIn(),
                        "create_time" => time(),
                        "expire_time" => time() + $accessToken->getExpireIn(),
                    ]);
                } else {
                    $exit->save([
                        "app_id" => $msg['app_id'],
                        "authority_id" => $msg['authority_id'],
                        "code" => $msg['code'],
                        "access_token" => $accessToken->getAccessToken(),
                        "refresh_token" => $accessToken->getRefreshToken(),
                        "expire_in" => $accessToken->getExpireIn(),
                        "create_time" => time(),
                        "expire_time" => time() + $accessToken->getExpireIn(),
                    ]);
                }
            }
        } catch (Exception $ex) {
            echo openssl_error_string(). "\r\n";
            echo $ex->getMessage() . "\r\n";
        }
    }

}